package com.hui.utils;

import com.alibaba.fastjson.JSON;
import com.hui.constants.RedisKeyConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户相关工具类
 */
@Component
public class UserCommonUtil {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final static String REQUEST_HEADER_AUTHORIZATION = "Authorization";
    private final static String TOKEN_TYPE = "bearer ";

    /**
     * 获取登录用户
     **/
    public LoginUser getLoginUser() {
        String authorization = request.getHeader(REQUEST_HEADER_AUTHORIZATION);

        if (StringUtils.isEmpty(authorization)) {
            return null;
        }

        String token = authorization.toLowerCase().replace(TOKEN_TYPE, "");

        String userTokenKey = RedisKeyConstant.TOKEN_USER + token;

        String result = stringRedisTemplate.opsForValue().get(userTokenKey);

        if (StringUtils.isEmpty(result)) {
            return null;
        }
        LoginUser loginUser = JSON.parseObject(result, LoginUser.class);

        return loginUser;
    }

    /**
     * 获取登录用户用户名
     **/
    public String getLoginUserName() {
        LoginUser user = getLoginUser();
        if (user == null) {
            return "";
        }
        return user.getUsername();
    }
}
